<template>
	<view class="container bg-fff">
		<u-navbar title=" " :background="{ background: $setting.colorTheme() }" :border-bottom="false" :is-back="false">
			<view style="width: 30rpx;"></view>
			<u-search placeholder="搜索商品" :show-action="false"  v-model="pageForm.search" height="56" @search="search" disabled @click="jump('/pages/categoty/product/search')"></u-search>
		</u-navbar>
		
		<view class="category-top">
			<scroll-view class="category-top-scroll" style="white-space: nowrap;" scroll-x="true">
				<view class="category-top-item" :class="{'category-top-item-select': categoryTopIndex == index}" v-for="(item,index) in categoryList" :key="index" @click="categoryTopChange(index)">
					<image :src="item.images.file_path"></image>
					<view>{{item.name}}</view> 
				</view>
			</scroll-view>
		</view>
		
		<view class="con flex">
			<scroll-view scroll-y="true" :style="{height: scrollHeight, width: '180rpx'}">
				<view class="category">
					<view class="category-item flex-center" :class="{'category-item-select': tabIndex == index}" v-for="(item,index) in categoryBelowList" :key="index" @click="categoryChange(index)">
						{{item.name}}
					</view>
				</view>
			</scroll-view>
			<scroll-view scroll-y="true" :scroll-into-view="scrollViewId" :style="{height: scrollHeight, flex: 1}" scroll-with-animation="true" @scrolltolower="lower" @scroll="lessscroll">
				
				<b-u-loading-txt :show="loaded?false:true" :txt="'数据加载中...'"/>
				
				<view class="product">
					<view class="product-item" v-for="(item,kindex) in productList" :key="kindex" :id="'indexed-list-'+kindex">
						<view class="product-item-title" :class="item.category.name==''?'nopadding':''">{{item.category.name}}</view>
						<view v-for="(oitem,oindex) in item.list" :key="oindex" class="product-item-list flex-align-center" @click="toDetail(oitem)">
							<image
							v-if="oitem['mark']"
							class="mark-at-top"
							:src="oitem['mark']['icon']"
							mode="widthFix"
							:style="
								oitem.mark.position == 0
									? 'top:' +
										oitem.mark.t_margin +
										'px; left:' +
										oitem.mark.l_margin +
										'px;'
									: 'top:' +
										oitem.mark.t_margin +
										'px; right:' +
										oitem.mark.l_margin +
										'px;'
							"
                            ></image>
							<view class="product-item-box-image">
								<view v-if="item.product_stock==0" class="product-item-box-bg">
									<view class="product-item-box-txt">补货中</view>
								</view>
								<image class="product-item-image" :src="oitem.product_image" lazy-load="true"></image>
							</view>
							<view class="product-item-con flex-column-space-between">
								<view class="product-item-name u-line-2">
									<span class="product-label" v-if="oitem['label']">{{oitem['label']['label_name']}}</span>
									{{oitem.product_name}}
								</view>
								<view v-if="oitem.discount_product_data.activity_type==1" class="seckill-activity">{{quantityDiscount(oitem.discount_product_data.rebate_json) }}</view>
								<view v-if="oitem.discount_product_data.activity_type==2" class="seckill-activity">首件{{ oitem.discount_product_data.first_price }}元 {{ oitem.discount_product_data.start_buy_num }}件起购</view>
								<view v-if="oitem.discount_product_data.activity_type==3" class="seckill-activity"><view class="seckill-activity-ele">赠</view>买{{ oitem.discount_product_data.buy_num }}赠{{ oitem.discount_product_data.gift_num }}</view>
								<view class="flex-space-between">
									<view class="product-item-price flex-align-center">
										<view><text>￥</text>{{oitem.product_sku.product_price}}</view>
										<text>￥{{oitem.product_sku.line_price}}</text>
									</view>
									<image class="product-item-cart" :src="$setting.imageUrl()+'cart_icon.png'"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		
	</view>
</template>

<script>
const statusBarHeight = uni.getSystemInfoSync().statusBarHeight+'px';
import { mapState } from "vuex";
export default {
	data() {
		return {
			firstLoad: true,
			categoryList: [],
			categoryTopIndex: 0,
			categoryBelowList: [],
			categoryIndex: 0,
			productList: [],
			cityIsChange: false,
			pageForm: {
				category_id: '',
				page: 1,
				search: '',
				sortType: 'all',
				list_rows: 20,
			},
			scrollHeight: '',
			myscrollheight:0,
			myscroll:[],
			scrollIndex:-1,
			temptop:0,
			scrollViewId:"indexed-list-0",
			isLeftClick:false,
			timer:null,
			tabIndex:0,
			loaded:false,
			share:{
					title: '',
					imageUrl:'',
            	},
		}
	},
	computed: {
        ...mapState(["maplocation",'vuex_stall_id']),
    },
	watch: {
        maplocation: {
            handler(val, oldVal) {
				this.cityIsChange = true
            },
            deep: true,
			immediate: true,
        },
    },
	async onLoad(opt) {
		if(this.vuex_stall_id>0){
			uni.reLaunch({
				url: '/pages/shop/stall_info'
			})
			return;
		}
		if(opt.topindex){
			this.categoryTopIndex = opt.topindex;
		}
		if(opt.smindex){
			this.categoryIndex = opt.smindex;
		}
		console.log('opt',opt)
		await this.getHttp();
		this.firstLoad = false
	},
	onTabItemTap(e) {
		console.log(e);
		// if(e.index == 1) {
		// 	console.log('gethttp2')
		// 	this.getHttp();
		// }
	},
	onShow() {
		if (this.cityIsChange && !this.firstLoad) {
			this.isListChange(this.categoryTopIndex)
		}
	},
	methods: {
		quantityDiscount(rebate_json){
			if(Array.isArray(rebate_json) && rebate_json.length>0){
				let formattedString = rebate_json.map(item => {  
					let discounts = (parseFloat(item.rebate) / 10).toFixed(1);
					let DisNumber = discounts.substring(0, discounts.indexOf('.'));
					let point = discounts.substring(discounts.indexOf('.') + 1,discounts.indexOf('.') + 2);
					let discount = DisNumber+(point>0?'.'+point:'');
					return `${item.num}件${discount}折`;  
				}).join(' '); 
			return formattedString
			}
		},
		getConfigDataDetail(){
			let params = {
				page_type:'diandan'
			}
			uni.$u.api.getConfigDataDetail(params).then(res => {
				let Detail =  res.data
				this.share.title = Detail.content
				this.share.imageUrl = Detail.image
			})
		},
		lessscroll(e){
			// this.myscrollheight = e.detail.scrollTop
			// 点击左侧导航栏引起的滚动不做判断
			let self = this;
			if(this.isLeftClick){
				this.isLeftClick = false
				return
			}
			// 防抖
			// if(this.timer){
			// 	clearTimeout(this.timer)
			// }
			// this.timer = setTimeout(()=>{
				let scrollTop = e.detail.scrollTop
				// console.log(self.myscroll)
				// console.log(scrollTop,'scrollTop')
				let index = self.myscroll.findIndex(it=>{
					return (it > scrollTop)
				}) -1
				if(index == -2) index = self.myscroll.length-1;
				if(index == self.tabIndex) return
				self.tabIndex = index
				// console.log(self.tabIndex)
			// },100)
		},
		toDetail(item){
			// console.log('item',item)
			if(item.activity_type=="discount"){
				this.jump('/pages/categoty/product/product_limited?id='+item.product_id)
			}else if(item.categorydetail.type==1){
				this.jump('/pages/categoty/product/product_no_cart?id='+item.product_id)
			}else{
				this.jump('/pages/categoty/product/product?id='+item.product_id)
			}
		},
		lower() {
			// if(this.loadmoreStatus == 'nomore') {
			// 	return;
			// }
			// this.pageForm.page++;
			// this.getProductLists();
		},
		jump(url) {
			uni.navigateTo({
				url: url
			})
		},
		categoryChange(e) {
			// this.categoryIndex = e;
			// this.pageForm.category_id = this.categoryBelowList[e].category_id;
			// this.search();
			console.log(e,"点击=====");
			this.isLeftClick = true;
			this.tabIndex = e;
			this.scrollViewId = 'indexed-list-'+e;		
		},
		categoryTopChange(e) {
			if(this.categoryTopIndex==e) return;
			this.categoryTopIndex = e;
			this.categoryBelowList = this.categoryList[e].child;
			this.getCategory();
			// if(uni.$u.test.isEmpty(this.categoryBelowList)) {
			// 	this.categoryBelowList = [];
			// 	this.productList = [];
			// } else {
			// 	this.categoryChange(0);
			// }
		},
		isListChange(e){
			let listlen = Number(this.categoryList.length)-1;
			if(listlen<e){
				e = listlen
			}
			this.categoryTopIndex = e;
			this.categoryBelowList = this.categoryList[e]?.child ?? [];
			this.getCategory();
		},
		getCategory() {
			uni.$u.api.getCategory().then(res => {
				this.categoryList = res.list;
				let listlen = Number(this.categoryList.length)-1;
				let TopIndex = this.categoryTopIndex
				if(listlen<TopIndex){
					this.categoryTopIndex = listlen
				}
				// this.categoryList = this.categoryList.filter(item => item.name!== '新人专享');
				this.categoryBelowList = this.categoryList[this.categoryTopIndex]?.child ?? [];
				// this.pageForm.category_id = this.categoryBelowList[this.categoryIndex].category_id;
				this.pageForm.category_id = this.categoryList[this.categoryTopIndex].category_id;
				this.cityIsChange = false
				this.$nextTick(() => {
					const query = uni.createSelectorQuery();
					query.in(this).select('.con').boundingClientRect();
					query.exec((res) => {
						this.scrollHeight = uni.getSystemInfoSync().windowHeight - res[0].top + 'px';
					})
				})
				
				this.search();
			})
		},
		async search() {
			this.loaded = false;
			this.pageForm.page = 1;
			this.productList = [];
			this.myscroll = [];
			// this.scrollViewId = "indexed-list-0";
			this.isLeftClick = false;
			this.timer = null;
			this.tabIndex = 0;
			await this.getProductLists();
			let self = this;
			// console.log('get categoryIndex',this.categoryIndex)
			setTimeout(function(){
				uni.createSelectorQuery().selectAll('.product-item-title').boundingClientRect(res=>{
					let temptop = 0;
					let thistop = 0;
					res.forEach(item => {
						if(temptop==0){
							temptop = item.top
							// console.log(item.top,'item.top');
							thistop = 0
						}else{
							thistop = item.top - temptop
						}
						self.myscroll.push(thistop)
						// console.log(item);
					});
					self.temptop = temptop
				}).exec();
				// console.log(self.myscroll);
			},100)
			if(self.categoryIndex>0){
				setTimeout(function(){
					let categoryIndex = self.categoryIndex
					self.categoryChange(categoryIndex)
					self.categoryIndex = 0;
					console.log('get ok')
				},500)
			}
		},
		async getProductLists() {
			return new Promise((resolve, reject) => {
				this.loadmoreStatus = 'loading';
				uni.$u.api.getCateProductLists(this.pageForm).then(async (res) => {
					console.log(res.list)
					this.productList = this.productList.concat(res.list);
					this.loadmoreStatus = 'loadmore';
					if(this.productList.length  == res.list.total) {
						this.loadmoreStatus = 'nomore';
					}
					this.loaded = true;
					resolve('ok');
				}).catch(ex => {
					console.log(ex)
					reject(ex)
				});
			})
		},
		getHttp() {
			this.getCategory();
			this.getConfigDataDetail()
		},
	},
}
</script>

<style lang="scss" scoped>
	.container {
		
		.category-top {
			padding: 20rpx 23rpx;
			height: 192rpx;
			
			.category-top-item {
				display: inline-block;
				font-size: 24rpx;
				color: #666666;
				text-align: center;
				margin-right: 60rpx;
				
				image {
					width: 96rpx;
					height: 96rpx;
					margin-bottom: 12rpx;
				}
			}
			
			.category-top-item-select {
				
				image {
					border: 3rpx solid $uni-color-theme;
					border-radius: 50%;
				}
				
				view {
					background: $uni-color-theme;
					border-radius: 16rpx;
					color: #ffffff;
				}
			}
		}
		
		.con {
			// margin-top: 30rpx;
			
			.category {
				background: #F8F9FA;
				width: 100%;
				min-height: 100%;
				
				.category-item {
					width: 100%;
					height: 110rpx;
					color: #666666;
				}
				
				.category-item-select {
					color: $uni-color-theme;
					background: #ffffff;
				}
			}
			
			.product {
				padding: 0;
				
				.product-item {
					display: flex;
					flex-direction: column;
					position: relative;
					
					.product-item-title,.product-item-fixed{
						font-size: 26rpx;
						line-height: 50rpx;
						background: #F8F9FA;
						font-weight: 300;
						width: 100%;
						padding:10rpx 0 10rpx 30rpx;
						z-index: 9999;
						position: sticky;
						/* #ifdef H5 */
						top: -1px;
						/* #endif */
						/* #ifdef MP-WEIXIN */
						top: 0;
						/* #endif */
					}
					.nopadding{
						padding:0 0 0 30rpx;
					}
					.product-fixed{
						position: fixed;
						top: calc(192rpx + $statusBarHeight);
						z-index: 9;
					}
					.product-item-list{
						position: relative;
						height: 219rpx;
						margin-bottom: 30rpx;
						padding-left: 16rpx;
						padding-right: 30rpx;
					}
					.product-item-box-image {
						position: relative;
						.product-item-box-bg {
							position: absolute;
								top: 0;
								left: 0;
								width: 165rpx;
								height: 165rpx;	
								background-color: rgba(0, 0, 0, 0.3);
								z-index: 99;
								opacity: 0.8;
								display: flex;
								justify-content: center;
								align-items: center;
							.product-item-box-txt {
								color: #fff;
								font-size: 22rpx;
								background-color: rgba(0, 0, 0, 0.8);
								border-radius: 30rpx;
								padding: 0 14rpx;
								white-space: nowrap;
								line-height: 32rpx;
								
							}
						}			
					}

					.product-item-image {
						width: 165rpx;
						height: 165rpx;
					}
					
					.product-item-con {
						margin-left: 30rpx;
						flex: 1;
						border-bottom: 1px solid #EBEBEB;
						padding-bottom: 30rpx;
						height: 100%;
						
						.product-item-name {
							font-size: 28rpx;
							color: #111111;
						}
						
						.product-item-price {
							
							view {
								font-size: 32rpx;
								color: $uni-color-theme;
								
								text {
									font-size: 22rpx;
									color: $uni-color-theme;
									text-decoration: none;
								}
							}
							
							text {
								font-size: 22rpx;
								text-decoration: line-through;
								color: #CCCCCC;
							}
						}
						
						.product-item-cart {
							width: 52rpx;
							height: 52rpx;
						}
						.seckill-activity {
							font-size: 20rpx;
							padding: 0 4rpx;
							margin: 10rpx 0;
							color: #bb0024;
							display: flex;
							align-items: center;
							border-radius: 8rpx;
							border: 1px solid #bb0024;
							display: inline-block;
							width: fit-content;
							.seckill-activity-txt {
								border: 1px solid #bb0024;
								border-radius: 50%;
								font-size: 18rpx;
								width: 26rpx;
								height: 26rpx;
								display: flex;
								align-items: center;
								justify-content: center;
								margin-left: 6rpx;
								display: inline-block;
								text-align: center;
								transform: scale(0.8);
							}
							.seckill-activity-ele {
								display: inline-block;
								padding: 0 4rpx;
								background-image: linear-gradient(to right, #bb0024, #fa0032);
								color: #fff;
								margin:0 10rpx 0 -4rpx;
								border-radius: 8rpx 0 8rpx 8rpx;
							}
						}
					}
				}
			}
		}
		
		::-webkit-scrollbar {
			display: none;
			width: 0 !important;
			height: 0 !important;
			-webkit-appearance: none;
			background: transparent;
			color: transparent;
		}
		
	}
	.mark-at-top {
		position: absolute;
		z-index: 80;
		width: 90rpx;
		// height: 100rpx;
	}
	.product-label {
		background: #BB0024;
		padding: 0rpx 10rpx 2rpx 10rpx;
		color: #fff;
		font-size: 24rpx;
		border-radius: 10rpx;
		margin-right: 10rpx;
	}
</style>
